package cn.xeblog.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.xeblog.commons.entity.Response;
import cn.xeblog.commons.entity.User;

import java.util.List;

/**
 * 历史响应服务抽象类
 *
 * @author anlingyi
 * @date 2021/9/11 4:58 下午
 */
public abstract class AbstractResponseHistoryService {

    /**
     * 添加历史消息
     *
     * @param response 消息
     */
    public final void addHistory(Response response) {
        addHistoryHandler(clone(response));
    }

    /**
     * 添加历史消息处理器
     *
     * @param response
     */
    protected abstract void addHistoryHandler(Response response);

    /**
     * 获取最近limit条历史消息
     *
     * @param limit 最近n条消息
     * @return 最近limit条历史消息列表
     */
    public abstract List<Response> getHistory(int limit);

    /**
     * 响应对象拷贝
     *
     * @param origin 源对象
     * @return 拷贝的对象
     */
    protected Response clone(Response origin) {
        Response resp = new Response();
        resp.setBody(origin.getBody());
        resp.setTime(origin.getTime());
        resp.setType(origin.getType());
        User user = origin.getUser();
        if (user != null) {
            User newUser = BeanUtil.copyProperties(user, User.class, "channel");
            resp.setUser(newUser);
        }
        return resp;
    }

}
